//
//  LTStudentLineView.m
//  LearnTeacher
//
//  Created by zyl_macbookpro on 2024/4/14.
//

#import "LTStudentLineView.h"
#import "Masonry.h"
static NSInteger baseLineCount = 5;//纵坐标个数
static NSInteger space = 37.5;//纵坐标个数
@implementation LTStudentLineView

{
    
    UILabel * titleLabel;//标题
    UIButton * arrowBtn;//标题箭头
    UILabel * unitLabel;//单位
    UILabel * desLabel1;//描述1
    UILabel * IdentifyLabel1;//颜色
    UILabel * desLabel2;//描述2
    UILabel * IdentifyLabel2;//颜色
    UILabel * desLabel3;//描述3
    UILabel * IdentifyLabel3;//颜色
    UIImageView * lastLineView;//最后一条背景线
    NSMutableArray * pointArray;//拐点数据
    NSMutableArray * xLabelArray;//横坐标
    NSMutableArray * btnArray;//按钮
    NSMutableArray * labelArray;//显示标签
    
    UIView *moveLine;
    
    CGPoint lastPoint;//最后一个坐标点
    
    CGFloat maxValue;//y轴最大值
}

-(void)setTitleStr:(NSString *)titleStr{
    
    _titleStr = titleStr;
    [arrowBtn setTitle:titleStr forState:UIControlStateNormal];
    //[arrowBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, -arrowBtn.imageView.frame.size.width, 0, arrowBtn.imageView.frame.size.width)];
    //[arrowBtn setImageEdgeInsets:UIEdgeInsetsMake(0, arrowBtn.titleLabel.bounds.size.width+5, 0, - arrowBtn.titleLabel.bounds.size.width)];
    //titleLabel.text = _titleStr;
}

-(void)setUnitStr:(NSString *)unitStr{
    
    _unitStr = unitStr;
    unitLabel.text = _unitStr;
}

-(void)setType:(NSInteger)type{
    
    _type = type;
}

-(void)setArrayX:(NSMutableArray *)arrayX{
    
    _arrayX = arrayX;
}

-(void)setArrayY:(NSMutableArray *)arrayY{
    
    _arrayY = arrayY;
    
    maxValue = [[_arrayY valueForKeyPath:@"@max.floatValue"] floatValue];
    if (maxValue <= 1.00) {
        maxValue = 100;
    }else{
        maxValue = maxValue * 100;
       // maxValue = ceilf(maxValue);
       // int remainder = (int)maxValue%10;
        //确保maxValue能被8整除
       // maxValue = maxValue + (10 - remainder);
    }
    
    //背景线条 + Y轴
    [self initBaseLineViewWithArrayY:nil];
    //X轴
    [self initXLineWithArrayX:_arrayX];
    self.bgScrollView.contentSize = CGSizeMake( (_arrayX.count)*45, self.bounds.size.height - 60);
   // self.bgScrollView.contentOffset = CGPointMake((_arrayX.count)*50 - CGRectGetWidth(self.bounds), 0);
    //获取拐点
    [self getInflectionPointWithArrayX:nil ArrayY:_arrayY color:0x4162FF];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
   
}
-(void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    
}
- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    
}
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
        labelArray = [NSMutableArray arrayWithCapacity:0];
        btnArray = [NSMutableArray arrayWithCapacity:0];
        pointArray  = [NSMutableArray arrayWithCapacity:0];
        xLabelArray = [NSMutableArray arrayWithCapacity:0];
        //maxValue = 100;
        [self addSubview:self.bgScrollView];
        [self initDescribleLables];
    }
    return self;
}

//显示lable
-(void)initDescribleLables{

    //单位
    unitLabel = [[UILabel alloc]init];
    unitLabel.textColor = rgba(153, 153, 153, 1);
    unitLabel.textAlignment = NSTextAlignmentCenter;
    unitLabel.font = RFontWithSize(11);
    [self addSubview:unitLabel];
   
    [unitLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.mas_top).with.offset(15);
        make.height.equalTo(@15.0f);
        make.left.equalTo(self.mas_left).with.offset(0.0f);
        make.right.equalTo(self.bgScrollView.mas_left).with.offset(5.0f);
    }];
}

//灰色背景线条 + 纵坐标
-(void)initBaseLineViewWithArrayY:(NSMutableArray *)array{
    
    
    for (int i = 0; i < baseLineCount; i++) {
        
        //灰色背景线条
        UIImageView * lineView = [[UIImageView alloc]init];
        lineView.backgroundColor = rgba(229, 229, 229, 1);
        [self.bgScrollView addSubview:lineView];
        
        if (i == baseLineCount-1)lastLineView = lineView;
        
        //纵坐标
        UILabel * labelY = [[UILabel alloc]init];
        labelY.textAlignment = NSTextAlignmentCenter;
        labelY.textColor = rgba(153, 153, 153, 1);
        labelY.font = MFontWithSize(10);
        //y坐标间隔
        double interval = maxValue/(baseLineCount -1)/100;
        labelY.text = [[NSString stringWithFormat:@"%.2f",ceil((baseLineCount - i -1)*interval*1.00)] stringByAppendingString:@"%"];
        [self addSubview:labelY];
        
        [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
            
            make.top.equalTo(self.bgScrollView.mas_top).with.offset(8+i*space);
            make.left.equalTo(self.bgScrollView.mas_left).with.offset(0.0f);
            make.right.equalTo(self.mas_right).with.offset(22.0f);
            make.height.equalTo(@0.5f);
        }];
        
        [labelY mas_makeConstraints:^(MASConstraintMaker *make) {
            
            make.left.equalTo(self.mas_left).with.offset(0.0f);
            make.right.equalTo(self.bgScrollView.mas_left).with.offset(5.0f);
            make.centerY.equalTo(lineView);
            make.height.equalTo(@17.0f);
            
        }];
    }
    
    if (moveLine.superview) {
        [moveLine removeFromSuperview];
    }
    
    moveLine = [[UIView alloc] initWithFrame:CGRectMake(50, 8, 1, (baseLineCount - 1)*space)];
    moveLine.hidden = YES;
    moveLine.backgroundColor = rgba(0, 0, 0, 0.15);
    [self.bgScrollView addSubview:moveLine];
}

//横坐标
-(void)initXLineWithArrayX:(NSMutableArray *)array{
    
    
    //横坐标
    for (int i = 0; i < array.count; i++) {
        
        UILabel * labelX = [[UILabel alloc]init];
        labelX.textAlignment = NSTextAlignmentCenter;
        labelX.textColor = rgba(102, 102, 102, 1);
        labelX.font = MFontWithSize(11);
        labelX.text = [NSString stringWithFormat:@"%@",array[i]];
        [self.bgScrollView addSubview:labelX];
        UIView *seperator = [[UIView alloc] initWithFrame:CGRectMake(i * (45), (baseLineCount - 1)*space + 8, 1, 7)];
        seperator.backgroundColor = [UIColor blackColor];
        [self.bgScrollView addSubview:seperator];
        [labelX mas_makeConstraints:^(MASConstraintMaker *make) {
            
            make.left.equalTo(self.bgScrollView.mas_left).with.offset(i * (45));
            make.top.equalTo(lastLineView.mas_bottom).with.offset(5.0f);
            make.width.mas_equalTo(45);
            make.height.equalTo(@17.0);
        }];
        [xLabelArray addObject:labelX];
    }
    
}

//获取拐点--注册
-(void)getInflectionPointWithArrayX:(NSMutableArray *)xArray ArrayY:(NSMutableArray *)yArray color:(long)color{
    
    [self layoutIfNeeded];
    NSMutableArray * midPointArray = [NSMutableArray arrayWithCapacity:0];
    for (UILabel * label in xLabelArray) {
        
        NSValue *point = [NSValue valueWithCGPoint:CGPointMake(label.center.x, 0)];
        [midPointArray addObject:point];
    }
    for (int i = 0; i < yArray.count; i++) {
        
        CGFloat currentData = [yArray[i] floatValue];
        CGFloat possionY = ((lastLineView.bottom - 8)/maxValue)*(maxValue - currentData * 100) + 8;
        NSValue * point = midPointArray[i];
        CGPoint  OriginPoint = point.CGPointValue;
        OriginPoint.y = possionY;
        NSValue * newPoint = [NSValue valueWithCGPoint:OriginPoint];
        [pointArray addObject:newPoint];
        
        //点击buton
        UIButton * pointBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        pointBtn.frame = CGRectMake(0, 0, 10, 10);
        pointBtn.layer.borderWidth = 1.7;
        pointBtn.layer.borderColor = [UIColor colorWithRed:34/255.0 green:136/255.0 blue:255/255.0 alpha:1.0].CGColor;
        [pointBtn setAllCornersWithCornerRadius:5];
        pointBtn.backgroundColor = LTWhiteColor;
        pointBtn.center = OriginPoint;
        pointBtn.tag = i + 1000;
        pointBtn.hidden = YES;
        [btnArray addObject:pointBtn];
        
    }
    
    //曲线
    //起点往前偏移
    CGPoint  originP = [[pointArray objectAtIndex:0] CGPointValue];
    CGPoint p1 = CGPointMake(originP.x - 27.5, originP.y);
    NSMutableArray * newPointArray = [NSMutableArray arrayWithArray:pointArray];
    NSValue *  point = [NSValue valueWithCGPoint:p1];
    [newPointArray insertObject:point atIndex:0];
    //直线的连线
    UIBezierPath *beizer = [UIBezierPath bezierPath];
    //beizer.
    [beizer moveToPoint:p1];
    
    /*遮罩*/
    UIBezierPath *bezier1 = [UIBezierPath bezierPath];
    bezier1.lineCapStyle = kCGLineCapRound;
    bezier1.lineJoinStyle = kCGLineJoinMiter;
    [bezier1 moveToPoint:p1];
    
    for (int i = 0;i<newPointArray.count;i++ ) {
        if (i != 0) {
            
            CGPoint prePoint = [[newPointArray objectAtIndex:i-1] CGPointValue];
            CGPoint nowPoint = [[newPointArray objectAtIndex:i] CGPointValue];
            
            [beizer addCurveToPoint:nowPoint controlPoint1:CGPointMake((nowPoint.x+prePoint.x)/2, prePoint.y) controlPoint2:CGPointMake((nowPoint.x+prePoint.x)/2, nowPoint.y)];
            
            [bezier1 addCurveToPoint:nowPoint controlPoint1:CGPointMake((nowPoint.x+prePoint.x)/2, prePoint.y) controlPoint2:CGPointMake((nowPoint.x+prePoint.x)/2, nowPoint.y)];
            
            if (i == newPointArray.count-1) {
                [beizer moveToPoint:nowPoint];//添加连线
                lastPoint = nowPoint;
            }
        }
    }
    
    /*遮罩*/
    CGFloat bgViewHeight = self.bgScrollView.bounds.size.height;
    //获取最后一个点的X值
    CGFloat lastPointX = lastPoint.x;
    //最后一个点对应的X轴的值
    CGPoint lastPointX1 = CGPointMake(lastPointX, bgViewHeight);
    [bezier1 addLineToPoint:lastPointX1];
    //回到原点
    [bezier1 addLineToPoint:CGPointMake(p1.x, bgViewHeight)];
    [bezier1 addLineToPoint:p1];
    
    //遮罩层
    CAShapeLayer *shadeLayer = [CAShapeLayer layer];
    shadeLayer.path = bezier1.CGPath;
    shadeLayer.fillColor = [UIColor greenColor].CGColor;
    
    
    //渐变图层
    CAGradientLayer *gradientLayer = [CAGradientLayer layer];
    gradientLayer.frame = CGRectMake(5, 0, 0, lastLineView.y - space*2 + 15);
    gradientLayer.startPoint = CGPointMake(0.5, 0);
    gradientLayer.endPoint = CGPointMake(0.5, 1);
    gradientLayer.colors = @[(__bridge id)[UIColor colorWithRed:121/255.0 green:171/255.0 blue:255/255.0 alpha:0.1].CGColor, (__bridge id)[UIColor colorWithRed:41/255.0 green:121/255.0 blue:255/255.0 alpha:0.1].CGColor];
    gradientLayer.locations = @[@(0), @(1.0f)];
    lastLineView.backgroundColor = rgba(140, 140, 140, 1);
    CALayer *baseLayer = [CALayer layer];
    [baseLayer addSublayer:gradientLayer];
    [baseLayer setMask:shadeLayer];
    [self.bgScrollView.layer addSublayer:baseLayer];
    
    CABasicAnimation *anmi1 = [CABasicAnimation animation];
    anmi1.keyPath = @"bounds";
    anmi1.duration = 1.0f;
    anmi1.toValue = [NSValue valueWithCGRect:CGRectMake(5, 0, 2*lastPoint.x, self.bgScrollView.bounds.size.height)];
    anmi1.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    anmi1.fillMode = kCAFillModeForwards;
    anmi1.autoreverses = NO;
    anmi1.removedOnCompletion = NO;
    [gradientLayer addAnimation:anmi1 forKey:@"bounds"];
    
    //*****************添加动画连线******************//
    CAShapeLayer *shapeLayer = [CAShapeLayer layer];
    shapeLayer.path = beizer.CGPath;
    shapeLayer.fillColor = [UIColor clearColor].CGColor;
    shapeLayer.strokeColor = rgba(41, 121, 255, 1).CGColor;
    shapeLayer.lineWidth = 2.0f;
    [self.bgScrollView.layer addSublayer:shapeLayer];
    
    CABasicAnimation *anmi = [CABasicAnimation animation];
    anmi.keyPath = @"strokeEnd";
    anmi.fromValue = [NSNumber numberWithFloat:0];
    anmi.toValue = [NSNumber numberWithFloat:1.0f];
    anmi.duration =1.0f;
    anmi.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    anmi.autoreverses = NO;
    
    [shapeLayer addAnimation:anmi forKey:@"stroke"];
    
    //添加点击btn
    for (UIButton * btn in btnArray) {
        [self.bgScrollView addSubview:btn];
    }
    
}

-(void)clickButtonAction:(UIButton *)sender{
    
    
    for (UIButton*btn in btnArray) {
        if (sender.tag == btn.tag) {
            btn.selected = YES;
        }else{
            btn.selected = NO;
        }
    }
    
    [self showDeslLabel:sender];
}

-(void)showDeslLabel:(UIButton *)sender{
    
    for (int i = 0; i < labelArray.count; i++) {
        
        UIButton * btn = labelArray[i];
        
        if (![self.bgScrollView.subviews containsObject:btn]) {
            [self.bgScrollView addSubview:btn];
        }
        
        if (sender.tag + 1000 == btn.tag) {
            btn.hidden = NO;
        }else{
            btn.hidden = YES;
        }
    }
    
}

-(void)switchSelectTypeAction{
    
    if ([self.delegate respondsToSelector:@selector(clickTopTypeAction:)]) {
        
        [self.delegate clickTopTypeAction:_type];
    }
    
}

-(UIScrollView *)bgScrollView{
    
    if (!_bgScrollView) {
        _bgScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(48, 30, self.bounds.size.width - 15 - 48, self.bounds.size.height - 30)];
        _bgScrollView.backgroundColor = [UIColor redColor];
        _bgScrollView.showsVerticalScrollIndicator = NO;
        _bgScrollView.showsHorizontalScrollIndicator = NO;
        _bgScrollView.backgroundColor = [UIColor whiteColor];
        _bgScrollView.contentSize = CGSizeMake((self.bounds.size.width - 15) * 3, self.bounds.size.height - 60);
        _bgScrollView.layer.cornerRadius = 6;
        _bgScrollView.bounces = NO;
        UILongPressGestureRecognizer *tap = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(tapClick:)];
        tap.minimumPressDuration = 0.2;
        [_bgScrollView addGestureRecognizer:tap];
    }
    return _bgScrollView;
}
- (void)tapClick:(UILongPressGestureRecognizer *)tap
{
    CGPoint p = [tap locationInView:self.bgScrollView];

    int index = p.x/45;
    moveLine.centerX = index*45 + 22;
    UIButton *pot = btnArray[index];
    for (UIButton *btn in btnArray) {
        btn.hidden = YES;
    }
    if (tap.state == UIGestureRecognizerStateEnded) {
        moveLine.hidden = YES;
        pot.hidden = YES;
    }else{
        moveLine.hidden = NO;
        pot.hidden = NO;
    }
}

@end
